<script setup>
import TnIcon from "@tuniao/tnui-vue3-uniapp/components/icon/src/icon.vue";
import { ref } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { get, post } from "@/request/request";
import { config } from "@/config";


const disCode = ref('');
const qrCode = ref('')
// 获取用户信息
disCode.value = uni.getStorageSync('disCode')

const onShareAppMessage = (res) => {
  if (res.from === 'button') {
  }
  return {
    title: '请家教，来找我',
    path: '/pages/index/index'
  }
}

// 添加屏幕尺寸的 ref
const screenWidth = ref(0);
const screenHeight = ref(0);

// 获取屏幕尺寸的函数
const getScreenSize = () => {
  const systemInfo = uni.getSystemInfoSync();
  screenWidth.value = systemInfo.screenWidth;
  screenHeight.value = systemInfo.screenHeight;
  console.log('屏幕宽度:', screenWidth.value);
  console.log('屏幕高度:', screenHeight.value);
}

onShow(() => {
  getScreenSize(); // 获取屏幕尺寸
  getOp();
  userInfo(); // 先获取用户信息
  // 删除这里的 getDistQrCode() 调用，因为要等 userInfo 获取到 disCode 后再调用
});

const userInfo = () => {
  get('/user_my').then(res => {
    console.log('user_my', res);
    if (res.data && res.data.disCode) {
      disCode.value = res.data.disCode;
      // 获取到 disCode 后再调用生成二维码
      getDistQrCode();
    } else {
      uni.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      });
    }
  }).catch(error => {
    console.error('获取用户信息失败:', error);
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'none'
    });
  });
}



const qrcodeSmall = async () => {
  try {
    // 先发送 HEAD 请求获取文件大小
    const headRes = await uni.request({
      url: config.baseUrl + '/file/wechat_qrcode.jpg',
      method: 'HEAD'
    });

    let totalSize = 0;
    if (headRes.header['Content-Range']) {
      const match = headRes.header['Content-Range'].match(/bytes \d+-\d+\/(\d+)/);
      if (match) {
        totalSize = parseInt(match[1]);
      }
    } else if (headRes.header['Content-Length']) {
      totalSize = parseInt(headRes.header['Content-Length']);
    }

    // 使用分片下载
    let fileData = [];
    const chunkSize = 1024 * 1024; // 1MB chunks
    let start = 0;

    while (start < totalSize) {
      const end = Math.min(start + chunkSize - 1, totalSize - 1);
      console.log(`下载分片: ${start}-${end}, 大小: ${end - start + 1} bytes`);

      const res = await uni.request({
        url: config.baseUrl + '/file/wechat_qrcode.jpg',
        method: 'GET',
        header: {
          'Range': `bytes=${start}-${end}`
        },
        responseType: 'arraybuffer'
      });

      if (res.statusCode !== 206) {
        // 如果服务器不支持断点续传，则直接下载完整文件
        return await downloadComplete();
      }

      if (!res.data || res.data.byteLength === 0) {
        throw new Error('分片数据为空');
      }

      fileData.push(res.data);
      start = end + 1;
    }

    // 合并所有分片
    const totalLength = fileData.reduce((acc, buffer) => acc + buffer.byteLength, 0);
    const mergedArrayBuffer = new Uint8Array(totalLength);
    let offset = 0;

    fileData.forEach((buffer) => {
      mergedArrayBuffer.set(new Uint8Array(buffer), offset);
      offset += buffer.byteLength;
    });

    // 转换为 base64
    const base64 = uni.arrayBufferToBase64(mergedArrayBuffer.buffer);
    qrCode.value = "data:image/jpeg;base64," + base64;
    console.log('文件下载成功');

  } catch (error) {
    console.error('下载失败:', error);
    // 如果分片下载失败，尝试直接下载完整文件
    await downloadComplete();
  }
}

// 完整下载文件的辅助函数
const downloadComplete = async () => {
  try {
    const res = await uni.request({
      url: config.baseUrl + '/file/wechat_qrcode.jpg',
      method: 'GET',
      responseType: 'arraybuffer'
    });

    if (res.statusCode === 200) {
      const base64 = uni.arrayBufferToBase64(res.data);
      qrCode.value = "data:image/jpeg;base64," + base64;
      console.log('完整文件下载成功');
    } else {
      throw new Error(`请求失败，状态码：${res.statusCode}`);
    }
  } catch (error) {
    console.error('完整下载失败:', error);
    uni.showToast({
      title: '文件下载失败',
      icon: 'none'
    });
  }
}

// 添加 shareCode 变量
const shareCode = ref('');

// 修改完整下载二维码的辅助函数
const downloadDistQrComplete = async () => {
  try {
    const res = await uni.request({
      url: config.baseUrl + '/public_api/get_dist_qr_code',
      method: 'POST',
      data: {
        path1: 'pages/index/index?disCode=' + disCode.value,
        width: 100,
        screen_w: screenWidth.value,
        screen_h: screenHeight.value
      },
      header: {
        'Content-Type': 'application/json'
      },
      responseType: 'arraybuffer'
    });

    if (res.statusCode === 200) {
      const base64 = uni.arrayBufferToBase64(res.data);
      // 保存到 shareCode 变量
      shareCode.value = "data:image/jpeg;base64," + base64;
      // 同时更新 qrCode 用于显示
      qrCode.value = shareCode.value;
      console.log('完整二维码下载成功');
    } else {
      throw new Error(`请求失败，状态码：${res.statusCode}`);
    }
  } catch (error) {
    console.error('完整下载失败:', error);
    uni.showToast({
      title: '获取二维码失败',
      icon: 'none'
    });
  }
}

// 同样修改 getDistQrCode 函数中成功时的处理
const getDistQrCode = async () => {
  try {
    // 直接发送 POST 请求获取文件
    const res = await uni.request({
      url: config.baseUrl + '/public_api/get_dist_qr_code',
      method: 'POST',
      data: {
        path1: 'pages/index/index?disCode=' + disCode.value,
        width: 100,
        screen_w: screenWidth.value,
        screen_h: screenHeight.value
      },
      header: {
        'Content-Type': 'application/json'
      },
      responseType: 'arraybuffer'
    });

    // 接受 200 或 206 状态码
    if ((res.statusCode === 200 || res.statusCode === 206) && res.data) {
      // 获取文件系统管理器
      const fs = uni.getFileSystemManager();
      // 定义临时文件路径
      const filePath = `${wx.env.USER_DATA_PATH}/qr_temp.jpg`;
      
      try {
        // 直接写入文件
        fs.writeFileSync(filePath, res.data, 'binary');
        
        // 更新图片路径
        shareCode.value = filePath;
        console.log('二维码生成成功，保存在:', filePath);
      } catch (fsError) {
        console.error('文件写入失败:', fsError);
        throw new Error('文件写入失败');
      }
    } else {
      throw new Error(`请求失败，状态码：${res.statusCode}`);
    }

  } catch (error) {
    console.error('获取二维码失败:', error);
    uni.showToast({
      title: '获取二维码失败',
      icon: 'none'
    });
  }
}

// 修改保存图片到相册的函数
const saveImageToPhotosAlbum = () => {
  if (!shareCode.value) {
    uni.showToast({
      title: '图片未准备好',
      icon: 'none'
    });
    return;
  }

  // 直接使用已下载的图片
  uni.saveImageToPhotosAlbum({
    filePath: shareCode.value,
    success: () => {
      uni.showToast({
        title: '图片保存成功',
        icon: 'success'
      });
    },
    fail: (error) => {
      console.error('保存失败:', error);
      uni.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  });
}



</script>

<template>
  <view class="share-qr">
    <view class="top-box"></view>
    <view class="qr-box">
      <view class="dist-page">
        <image :src="shareCode" mode="aspectFit" style="width: 670rpx; height: 960rpx;" />
      </view>
    </view>
    <view class="qr-share-btn">
      <button class="qr-share-btn-item" open-type="share" @click="onShareAppMessage">
        <TnIcon name="share-triangle" :size="45" />
        <text>分享按钮</text>
      </button>
      <button class="qr-share-btn-item-t" @click="saveImageToPhotosAlbum">保存相册</button>
    </view>
  </view>
</template>


<style scoped lang="scss">
.share-qr {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;

  .top-box {
    width: 100%;
    height: 240rpx;
    background: #0052D9;
  }

  .qr-box {
    margin-top: -150rpx;
    padding: 20rpx;
    background: #fff;
    border-radius: 18rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    .dist-page {
      background-color: #fff;
      overflow: hidden;
      position: relative;
      
      image {
        width: 300rpx;
        height: 600rpx;
        display: block;
        margin: 0 auto;  // 居中显示
      }
    }
  }

  .qr-share-btn {
    margin-top: 100rpx;
    width: 100%;
    height: 160rpx;
    display: flex;
    align-items: center;
    justify-content: space-around;

    .qr-share-btn-item {
      width: 335rpx;
      height: 96rpx;
      border-radius: 12rpx;
      background: #F2F3FF;
      border: 2rpx solid #0052D9;
      color: #0052D9;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .qr-share-btn-item-t {
      width: 335rpx;
      height: 96rpx;
      background: #0052D9;
      color: #FFF;
      border-radius: 12rpx;
    }
  }
}
</style>
